package edu.asu.sefcom.extract.profile.data;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.neo4j.graphdb.GraphDatabaseService;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

public class GoogleTranslate {

//	static long sleeptime = 1 * 60 * 1000;
	static long sleeptime = 10 * 1000;
	protected GraphDatabaseService graphDB;

	public void setGraphDB(GraphDatabaseService graphDB) {
		this.graphDB = graphDB;
	}

	public static String translate(String toTransate) throws Exception {
		// Set the HTTP referrer to your website address.
		Translate.setHttpReferrer("http://www.asu.edu");

		StringBuffer buffer = new StringBuffer("");
		String[] arr1 = split(toTransate);
		String translatedText = null;
		for (String textTrans : arr1) {
			try {
				translatedText = Translate.execute(textTrans, Language.RUSSIAN,
						Language.ENGLISH);
				buffer.append(translatedText);
			} catch (Exception e) {
				e.printStackTrace();
				translatedText = "Empty";
				sleepforsometime();
			}
		}
		System.out.println(" translation:-" + buffer.toString());

		return buffer.toString();
	}

	private static void sleepforsometime() {
		try {
			System.out.println(" going to sleep for -" + sleeptime);
			Thread.currentThread().sleep(sleeptime);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public static final int maxLen = 300;

	public static String[] split(String str) {

		// get the length of the original string
		int origLen = str.length();

		// calculate the number of substrings we'll need to make
		int splitNum = origLen / maxLen;
		if (origLen % maxLen > 0)
			splitNum += 1;

		// initialize the result array
		String[] splits = new String[splitNum];

		// for each substring...
		for (int i = 0; i < splitNum; i++) {

			// the substring starts here
			int startPos = i * maxLen;

			// the substring ends here
			int endPos = startPos + maxLen;

			// make sure we don't cause an IndexOutOfBoundsException
			if (endPos > origLen)
				endPos = origLen;

			// make the substring
			String substr = str.substring(startPos, endPos);

			// stick it in the result array
			splits[i] = substr;
		}

		// return the result array
		return splits;
	}

}